package com.kili.file.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kili.file.controller.request.FileUploadRequest;
import com.kili.file.dao.FileMapper;
import com.kili.file.modal.File;
import com.kili.file.service.FileHandleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Objects;

import static com.kili.file.modal.File.ENABLE;

/**
 * @author Gordon
 * @version 2019/4/4
 */
@Service
@Slf4j
public class FileHandlerServiceImpl extends ServiceImpl<FileMapper, File> implements FileHandleService {

    private static final int MAX_RETRY = 5;

    @Override
    public void save(FileUploadRequest req) {
        File file = new File();
        BeanUtils.copyProperties(req, file);

        file.setId(IdWorker.getIdStr());
        file.setName(req.getFile().getOriginalFilename());
        file.setCreateTime(req.getRequestTime());
        file.setUpdateTime(req.getRequestTime());
        if (Objects.isNull(file.getStatus())) {
            file.setStatus(ENABLE);
        }
        for (int a = 0; ; a++) {
            try {
                Assert.state(baseMapper.insert(file) > 0, "file info storage error");
                break;
            } catch (Exception ex) {
                if (a > MAX_RETRY) {
                    log.error("file info storage error req={}", req, ex);
                    break;
                }
            }
        }
    }
}
